import Vue from 'vue'
import { login, logout, phoneLogin, casValidateLogin } from '@/views/user/service.js'
import { thirdLogin } from '@/views/user/third/service.js'
import { switchTenant } from '@/views/system/user/service.js'
import { getTenantUserInfoResult } from '@/views/tenant/service.js'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  USER_AUTH,
  SYS_BUTTON_AUTH,
  UI_CACHE_DB_DICT_DATA,
  TENANT_ID,
  CACHE_INCLUDED_ROUTES,
  IS_SUPER_TENANT,
  IS_TENANT_ADMIN,
  IS_MULTI_TENANT,
  SET_SYSTEM_CONFIG
} from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { getSysCustomConfig } from '@/views/sysConfig/sysCustom/service.js'
import { queryPermissionsByUser,queryDictItems } from '@/api/api'

const user = {
  state: {
    token: '',
    username: '',
    realname: '',
    tenantid: '',
    isSuperTenant: '',
    isTenantAdmin: '',
    isMultiTenant: '',
    welcome: '',
    avatar: '',
    permissionList: [],
    info: {},
      // 系统安全模式
    sysSafeMode: null,
    systemConfig: {
      iconUrl: undefined,
      title: '',
      icoUrl: undefined
    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TENANT: (state, id) => {
      state.tenantid = id
    },
    SET_SYS_SAFE_MODE: (state, sysSafeMode) => {
      if (typeof sysSafeMode === 'boolean') {
        state.sysSafeMode = sysSafeMode
      } else {
        state.sysSafeMode = false
      }
    },
    SET_IS_SUPER_TENANT: (state, is) => {
      state.isSuperTenant = is
    },
    SET_IS_TENANT_ADMIN: (state, is) => {
      state.isTenantAdmin = is
    },
    SET_IS_MULTI_TENANT: (state, is) => {
      state.isMultiTenant = is
    },
    SET_SYSTEM_CONFIG: (state, is) => {
      state.systemConfig = is
    }
  },
  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        casValidateLogin(userInfo)
          .then(response => {
            console.log('----cas 登录--------', response)
            if (response.success) {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              /** 默认获取第一个租户，调到系统在让选择 */
              const tenantIds = userInfo.relTenantIds;
              if (tenantIds) {
                let ids = tenantIds.split(',');
                if (ids && ids.length > 0) {
                  let isMultiTenant = ids.length > 1;
                  this.dispatch('saveIsMultiTenant', isMultiTenant);
                  this.dispatch('saveTenant', ids[0]).then(response => {
                    resolve(response);
                  });
                } else {
                  this.dispatch('saveIsMultiTenant', false);
                  resolve(response);
                }
              } else {
                resolve(response)
              }
            } else {
              resolve(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(async response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              await queryDictItems().then(res => {  
              if (res.success) { 
                  Vue.ls.set(UI_CACHE_DB_DICT_DATA, res.result, 7 * 24 * 60 * 60 * 1000)
                  }
              })
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo)
          .then(async response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              await queryDictItems().then(res => {  
              if (res.success) { 
                  Vue.ls.set(UI_CACHE_DB_DICT_DATA, res.result, 7 * 24 * 60 * 60 * 1000)
                  }
              })
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        queryPermissionsByUser()
          .then(response => {
            if (response.success) {
              const menuData = response.result.menu
              const authData = response.result.auth
              const allAuthData = response.result.allAuth
              // Vue.ls.set(USER_AUTH,authData);
              sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
              sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
              if (menuData && menuData.length > 0) {
                // update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
                menuData.forEach((item, index) => {
                  if (item['children']) {
                    let hasChildrenMenu = item['children'].filter(i => {
                      return !i.hidden || i.hidden == false
                    })
                    if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
                      item['hidden'] = true
                    }
                  }
                })
                // console.log(" menu show json ", menuData)
                // update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
                commit('SET_PERMISSIONLIST', menuData)
                resolve(response)
              } else {
                // eslint-disable-next-line prefer-promise-reject-errors
                reject('您没有登录认证中心的权限')
              }
            } else {
              reject(response)
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        let logoutToken = state.token
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        Vue.ls.remove(ACCESS_TOKEN)
        Vue.ls.remove(USER_INFO)
        Vue.ls.remove(USER_NAME)
        Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
        Vue.ls.remove(CACHE_INCLUDED_ROUTES)
        // console.log('logoutToken: '+ logoutToken)
        logout(logoutToken)
          .then(() => {
            if (process.env.VUE_APP_SSO == 'true') {
              let sevice = 'http://' + window.location.host + '/'
              let serviceUrl = encodeURIComponent(sevice)
              window.location.href = process.env.VUE_APP_CAS_BASE_URL + '/logout?service=' + serviceUrl
            }
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        thirdLogin(param.token, param.thirdType)
          .then(response => {
            if (response.code == '200') {
              const result = response.result
              const userInfo = result.userInfo
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)
              commit('SET_INFO', userInfo)
              commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
              commit('SET_AVATAR', userInfo.avatar)
              resolve(response)
            } else {
              reject(response)
            }
          })
      })
    },
    saveTenant({ commit }, id) {
      Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
      let userInfo = Vue.ls.get(USER_INFO)
      return new Promise((resolve, reject) => {
        let userId = userInfo.id;
        let tenantId = id;
        getTenantUserInfoResult(tenantId, userId).then(response => {
          if (response.success) {
            Vue.ls.set(IS_SUPER_TENANT, response.result.isSuperTenant, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(IS_TENANT_ADMIN, response.result.isAdmin ? 1 : 0, 7 * 24 * 60 * 60 * 1000)
            commit('SET_IS_SUPER_TENANT', response.result.isSuperTenant)
            commit('SET_IS_TENANT_ADMIN', response.result.isAdmin)
          } else {
            Vue.ls.set(IS_SUPER_TENANT, false, 7 * 24 * 60 * 60 * 1000)
            Vue.ls.set(IS_TENANT_ADMIN, false, 7 * 24 * 60 * 60 * 1000)
            commit('SET_IS_SUPER_TENANT', false)
            commit('SET_IS_TENANT_ADMIN', false)
          }
          commit('SET_TENANT', tenantId)
          let params = {
            'userId': userId,
            'tenantId': tenantId
          }
          this.dispatch('switchTenant', params);
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
      })
    },
    saveIsMultiTenant({ commit }, isMultiTenant) {
      Vue.ls.set(IS_MULTI_TENANT, isMultiTenant, 7 * 24 * 60 * 60 * 1000)
      commit('SET_IS_MULTI_TENANT', isMultiTenant)
    },
    // 在进入页面时获取系统个性化配置
    getSystemConfig({ commit }) {
      // 设置默认图标
      commit('SET_SYSTEM_CONFIG', SET_SYSTEM_CONFIG);
      return new Promise((resolve, reject) => {
        let params = {
          authFlag: 1
        };
        getSysCustomConfig(Vue.ls.get(TENANT_ID), params).then(res => {
          if (res.success && res.result) {
            let iconUrl = res.result.iconUrl ? res.result.iconUrl : SET_SYSTEM_CONFIG.iconUrl
            let title = res.result.title ? res.result.title : SET_SYSTEM_CONFIG.title
            let icoUrl = res.result.icoUrl ? res.result.icoUrl : SET_SYSTEM_CONFIG.icoUrl
            commit('SET_SYSTEM_CONFIG', {
              iconUrl: iconUrl,
              title: title,
              icoUrl: icoUrl
            })
          }
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
      })
    },

    // 设置系统个性化配置 iconUrl or title
    setSystemConfig({ state }) {
      let icoUrl = state.systemConfig.icoUrl
      let title = state.systemConfig.title
      if (title) {
        document.querySelectorAll('head  title')[0].text = title
      }
      if (icoUrl) {
        // local  window._CONFIG['staticDomainURL'] + '/'
        document.querySelector("link[rel*='icon']").href = icoUrl
      }
    },
    // 切换租户 上报日志
    switchTenant({ commit }, params) {
      let userId = params.userId;
      let tenantId = params.tenantId;
      return new Promise((resolve, reject) => {
        switchTenant(userId, tenantId).then(response => {
          if (response.success) {
            console.log('switch Tenant success...');
          } else {
            console.log('switch Tenant failure...');
          }
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
